package com.data.modules.gd.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.data.common.util.HttpClientUtil;
import com.data.common.util.MyDateUtils;
import com.data.modules.gd.entity.GdLiveChannel;
import com.data.modules.gd.entity.GdProgramme;
import com.data.modules.gd.mapper.GdLiveChannelMapper;
import com.data.modules.gd.service.IGdLiveChannelService;
import com.data.modules.gd.service.IGdProgrammeService;
import com.data.modules.gd.vo.LivechanneVo;
import com.data.modules.gd.vo.ScheduleVo;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 广电频道表
 * @Author: data-boot
 * @Date:   2022-11-29
 * @Version: V1.0
 */
@Service
@Slf4j
public class GdLiveChannelServiceImpl extends ServiceImpl<GdLiveChannelMapper, GdLiveChannel> implements IGdLiveChannelService {

    @Autowired
    private IGdProgrammeService programmeService;
    @Override
    public void synChannelInfo(String parameter) {

        String url = "http://epg.hbcatv.cn/api/LiveChannelList?checkkey=0x201307151500&data=ZGV2aWQ9MDAwMDAwMTkyMDMyMTg4MDQmZG09aHVhd2VpJnBhcnR5PTVneXVuYXBwJnB0PTImZHQ9OSZ1PTVneXVuYXBw";
        String result =  HttpClientUtil.doGet(url);

        byte[] decodedBytes = Base64.getDecoder().decode(result);
        String decodedString = new String(decodedBytes);

        JSONObject jsonObj = JSON.parseObject(decodedString);

        String arrObj = jsonObj.getString("ChannelList");
        String resultCode = jsonObj.getString("ResultCode");
        String resultDesc = jsonObj.getString("ResultDesc");

        log.info("===广电频道接口返回resultCode==:{}",resultCode);
        log.info("===广电频道接口返回resultDesc==:{}",resultDesc);

        List<LivechanneVo> inventoryDTOs = JSON.parseArray(arrObj, LivechanneVo.class);
        if(ObjectUtil.isEmpty(inventoryDTOs)){
            return;
        }

        for(LivechanneVo vo :inventoryDTOs){

            GdLiveChannel channel = new GdLiveChannel();
            channel.setChannelId(vo.getChannelId());
            channel.setCategoryName(vo.getCategoryName());
            channel.setCategoryId(vo.getCategoryId());
            channel.setChannelNumber(vo.getChannelNumber());
            channel.setHlsUrl(vo.getHlsUrl());
            channel.setLiveChannelType(vo.getLiveChannelType());
            channel.setLogoUrl(vo.getLogoURI());
            channel.setMultiUrl(vo.getMultiUrl());
            channel.setName(vo.getName());
            channel.setRemark(vo.getDesc());
            channel.setShiftTimeStamp(vo.getShiftTimeStamp());
            channel.setViewPeriod(vo.getViewPeriod());

            List<GdLiveChannel> list = this.lambdaQuery().eq(GdLiveChannel::getChannelId,channel.getChannelId()).list();

            if(ObjectUtil.isNotEmpty(list)){

                this.removeById(list.get(0).getId());
            }
            this.save(channel);

            synChannelSchedule(channel,parameter);

        }

    }

    /**
     * 自动打标签
     * @param parameter
     */
    @Override
    public void autoIsLable(String parameter) {
        //获取输入参数 自动 +1 天 打标签

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = new Date();
        if(ObjectUtil.isNotEmpty(parameter)){

            try {
                Date starDate = sdf.parse(parameter);

                String starTime = MyDateUtils.getStrPreOrNextDay(starDate,0);
                String endTime = MyDateUtils.getStrPreOrNextDay(starDate,1);

                //programmeService.autoLable(starTime,endTime);

                List<GdProgramme> list = programmeService.lambdaQuery().eq(GdProgramme::getStartDate,starTime)
                        .eq(GdProgramme::getIsLabel,1)
                        .list();

                if(ObjectUtil.isNotEmpty(list)){

                    list.stream().forEach(x->{

                        programmeService.lambdaUpdate().eq(GdProgramme::getStartDate,endTime).eq(GdProgramme::getIsLabel,0)
                                .eq(GdProgramme::getName,x.getName())
                                .eq(GdProgramme::getChannelId,x.getChannelId())
                                .eq(GdProgramme::getStartTime,x.getStartTime())
                                .set(GdProgramme::getType,x.getType())
                                .set(GdProgramme::getIsLabel,1).update();
                    });

                }

            } catch (ParseException e) {
                log.error("autoIsLable异常"+e.getMessage(),e);
            }

        }else{

            String starTime = MyDateUtils.getStrPreOrNextDay(new Date(),0);
            String endTime = MyDateUtils.getStrPreOrNextDay(new Date(),1);

            List<GdProgramme> list = programmeService.lambdaQuery().eq(GdProgramme::getStartDate,starTime)
                    .eq(GdProgramme::getIsLabel,1)
                    .list();

            if(ObjectUtil.isNotEmpty(list)){

                list.stream().forEach(x->{

                    programmeService.lambdaUpdate().eq(GdProgramme::getStartDate,endTime).eq(GdProgramme::getIsLabel,0)
                            .eq(GdProgramme::getName,x.getName())
                            .eq(GdProgramme::getChannelId,x.getChannelId())
                            .eq(GdProgramme::getStartTime,x.getStartTime())
                            .set(GdProgramme::getType,x.getType())
                            .set(GdProgramme::getIsLabel,1).update();
                });

            }


        }

    }

    @Override
    public void synDayChannelInfo(String parameter) {
        String url = "http://epg.hbcatv.cn/api/LiveChannelList?checkkey=0x201307151500&data=ZGV2aWQ9MDAwMDAwMTkyMDMyMTg4MDQmZG09aHVhd2VpJnBhcnR5PTVneXVuYXBwJnB0PTImZHQ9OSZ1PTVneXVuYXBw";
        String result =  HttpClientUtil.doGet(url);

        byte[] decodedBytes = Base64.getDecoder().decode(result);
        String decodedString = new String(decodedBytes);

        JSONObject jsonObj = JSON.parseObject(decodedString);

        String arrObj = jsonObj.getString("ChannelList");
        String resultCode = jsonObj.getString("ResultCode");
        String resultDesc = jsonObj.getString("ResultDesc");

        log.info("===广电频道接口返回resultCode==:{}",resultCode);
        log.info("===广电频道接口返回resultDesc==:{}",resultDesc);

        List<LivechanneVo> inventoryDTOs = JSON.parseArray(arrObj, LivechanneVo.class);
        if(ObjectUtil.isEmpty(inventoryDTOs)){
            return;
        }

        for(LivechanneVo vo :inventoryDTOs){

            GdLiveChannel channel = new GdLiveChannel();
            channel.setChannelId(vo.getChannelId());
            channel.setCategoryName(vo.getCategoryName());
            channel.setCategoryId(vo.getCategoryId());
            channel.setChannelNumber(vo.getChannelNumber());
            channel.setHlsUrl(vo.getHlsUrl());
            channel.setLiveChannelType(vo.getLiveChannelType());
            channel.setLogoUrl(vo.getLogoURI());
            channel.setMultiUrl(vo.getMultiUrl());
            channel.setName(vo.getName());
            channel.setRemark(vo.getDesc());
            channel.setShiftTimeStamp(vo.getShiftTimeStamp());
            channel.setViewPeriod(vo.getViewPeriod());

            List<GdLiveChannel> list = this.lambdaQuery().eq(GdLiveChannel::getChannelId,channel.getChannelId()).list();

            if(ObjectUtil.isNotEmpty(list)){

                this.removeById(list.get(0).getId());
            }
            this.save(channel);

            synDayChannelSchedule(channel,parameter);

        }
    }

    /**
     * 同步当天广电数据
     * @param channelInfo
     * @param parameter
     */
    private void synDayChannelSchedule(GdLiveChannel channelInfo,String parameter){

        if(ObjectUtil.isNotEmpty(parameter)){
            synGdScheduleInfo(parameter,channelInfo);
        }else{
            synGdScheduleInfo(MyDateUtils.getStrPreOrNextDay(new Date(),0),channelInfo);
        }

    }



    /**
     * 判断是否循环获取广电节目单信息
     * @param channelInfo
     * @param parameter
     */
    private void synChannelSchedule(GdLiveChannel channelInfo,String parameter){

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = new Date();
        if(ObjectUtil.isNotEmpty(parameter)){
            try {
                Date starDate = sdf.parse(parameter);
                int betweenDay = MyDateUtils.getBetweenDay(starDate,date);
                if(betweenDay <0){
                    starDate = new Date();
                    betweenDay =  Math.abs(betweenDay);
                }

                for(int i = 0; i < betweenDay; i++) {

                    synGdScheduleInfo(MyDateUtils.getStrPreOrNextDay(starDate,i),channelInfo);

                }

            } catch (ParseException e) {
                log.error("sysEmpCostInfo异常"+e.getMessage(),e);
            }
        }else{

            synGdScheduleInfo(MyDateUtils.getStrPreOrNextDay(new Date(),2),channelInfo);

        }
    }

    /**
     * 获取指定时间的 获取广电节目单信息
     * @param preOrNextDay
     */
    private void synGdScheduleInfo(String preOrNextDay,GdLiveChannel channelInfo) {

        //删除7天之前的旧数据
        programmeService.deleteData();

        StringBuffer stringBuffer = new StringBuffer();

        Map<String,Object> map = new HashMap<>();
        map.put("username","sm-test");
        map.put("oid","2159");
        map.put("dm","huawei");
        map.put("id",channelInfo.getChannelId());
        map.put("devid","00000019203218804");
        map.put("party","5gyunapp");
        map.put("pt",2);
        map.put("dt",9);
        map.put("date",preOrNextDay);

        for (String string : map.keySet()) {
            stringBuffer.append(string).append("=").append(map.get(string)).append("&");

        }
        stringBuffer.deleteCharAt(stringBuffer.length()-1);

        String encodedString = Base64.getEncoder().encodeToString(stringBuffer.toString().getBytes());

        //指定查询某一天的节目单，格式：yyyyMMdd
        String url = "http://epg.hbcatv.cn/api/ChannelSchedule?checkkey=0x201307151500&data="+encodedString;
        String result =  HttpClientUtil.doGet(url);

        log.info("===调用广电获取节目单接口url==:{}",url);

        byte[] decodedBytes = Base64.getDecoder().decode(result);
        String decodedString = new String(decodedBytes);

        JSONObject jsonObj = JSON.parseObject(decodedString);

        String arrObj = jsonObj.getString("ScheduleList");
        String resultCode = jsonObj.getString("ResultCode");
        String resultDesc = jsonObj.getString("ResultDesc");
        log.info("===广电节目接口返回resultCode==:{}",resultCode);
        log.info("===广电节目接口resultDesc==:{}",resultDesc);

        List<ScheduleVo> scheduleVos = JSON.parseArray(arrObj, ScheduleVo.class);

        if(ObjectUtil.isNotEmpty(scheduleVos)){
            for(ScheduleVo vo:scheduleVos){
                GdProgramme programme = new GdProgramme();
                programme.setDispFlag(vo.getDispFlag());
                programme.setDuration(vo.getDuration());
                programme.setEndTimestamp(vo.getEndTimestamp());

                String name = vo.getName();
                String realName = "";
                String remark ="";
                if(ObjectUtil.contains(name,"(")){
                    realName = StringUtils.substringBefore(name, "(");
                    remark =StringUtils.substringBetween(name,"(",")");
                    programme.setRemark(remark);
                    programme.setName(realName);
                }else{
                    programme.setRemark(vo.getStartDate()+vo.getStartTime());
                    programme.setName(name);
                }
                programme.setRealName(vo.getName());
                programme.setReqTime(preOrNextDay);
                programme.setScheduleId(vo.getScheduleID());
                programme.setScheduleType(vo.getScheduleType());
                programme.setStartDate(vo.getStartDate());
                programme.setStartTime(vo.getStartTime());
                programme.setStartTimestamp(vo.getStartTimestamp());
                programme.setStatus(vo.getStatus());
                programme.setWatermarkPos(vo.getWatermarkPos());
                programme.setWatermarkUrl(vo.getWatermarkURI());
                programme.setChannelId(channelInfo.getChannelId());
                programme.setChannelNumber(channelInfo.getChannelNumber());
                programme.setChannelName(channelInfo.getName());
                programme.setCategoryName(channelInfo.getCategoryName());//频道名称

                //通过
               List<GdProgramme> list =  programmeService.lambdaQuery().eq(GdProgramme::getChannelId,programme.getChannelId()).eq(GdProgramme::getChannelName,programme.getChannelName())
                        .eq(GdProgramme::getStartDate,programme.getStartDate())
                        .eq(GdProgramme::getStartTime,programme.getStartTime()).list();
               if(ObjectUtil.isNotEmpty(list)){
                   programmeService.removeById(list.get(0).getId());
               }

               programmeService.save(programme);

            }
        }

    }

}
